package top.continew.ai.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author: lonni
 * @CreateTime: 2025-08-20  22:30
 * @Description:
 */
@RestController
@RequestMapping("/api/file")
public class FileController {

    @Value("${file.upload-dir:/tmp/uploads}")
    private String uploadDir;

    /**
     * 普通文件上传
     */
    @PostMapping("/upload")
    public ResponseEntity<Map<String, Object>> uploadFile(@RequestParam("file") MultipartFile file) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建上传目录
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

            // 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            response.put("success", true);
            response.put("message", "文件上传成功");
            response.put("filename", uniqueFilename);
            response.put("originalFilename", originalFilename);
            response.put("size", file.getSize());

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "文件上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 分片上传 - 初始化
     */
    @PostMapping("/chunk/init")
    public ResponseEntity<Map<String, Object>> initChunkUpload(@RequestParam("filename") String filename,
                                                               @RequestParam("totalChunks") Integer totalChunks,
                                                               @RequestParam("chunkSize") Long chunkSize) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 创建临时目录用于存储分片
            String uploadId = UUID.randomUUID().toString();
            Path chunkDir = Paths.get(uploadDir, "chunks", uploadId);
            Files.createDirectories(chunkDir);

            response.put("success", true);
            response.put("uploadId", uploadId);
            response.put("message", "分片上传初始化成功");

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "初始化失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 分片上传 - 上传单个分片
     */
    @PostMapping("/chunk/upload")
    public ResponseEntity<Map<String, Object>> uploadChunk(@RequestParam("file") MultipartFile file,
                                                           @RequestParam("uploadId") String uploadId,
                                                           @RequestParam("chunkIndex") Integer chunkIndex) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 检查参数
            if (file.isEmpty()) {
                response.put("success", false);
                response.put("message", "分片文件不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建分片存储路径
            Path chunkDir = Paths.get(uploadDir, "chunks", uploadId);
            if (!Files.exists(chunkDir)) {
                response.put("success", false);
                response.put("message", "无效的uploadId");
                return ResponseEntity.badRequest().body(response);
            }

            // 保存分片文件
            String chunkFilename = String.format("%05d", chunkIndex);
            Path chunkPath = chunkDir.resolve(chunkFilename);
            Files.copy(file.getInputStream(), chunkPath, StandardCopyOption.REPLACE_EXISTING);

            response.put("success", true);
            response.put("message", "分片上传成功");
            response.put("chunkIndex", chunkIndex);

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "分片上传失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 分片上传 - 完成分片上传
     */
    @PostMapping("/chunk/complete")
    public ResponseEntity<Map<String, Object>> completeChunkUpload(@RequestParam("uploadId") String uploadId,
                                                                   @RequestParam("filename") String filename,
                                                                   @RequestParam("totalChunks") Integer totalChunks) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 分片目录
            Path chunkDir = Paths.get(uploadDir, "chunks", uploadId);
            if (!Files.exists(chunkDir)) {
                response.put("success", false);
                response.put("message", "无效的uploadId");
                return ResponseEntity.badRequest().body(response);
            }

            // 创建目标文件
            String fileExtension = "";
            if (filename.contains(".")) {
                fileExtension = filename.substring(filename.lastIndexOf("."));
            }
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
            Path targetFilePath = Paths.get(uploadDir, uniqueFilename);

            // 合并所有分片
            try (var outputStream = Files.newOutputStream(targetFilePath)) {
                for (int i = 0; i < totalChunks; i++) {
                    String chunkFilename = String.format("%05d", i);
                    Path chunkPath = chunkDir.resolve(chunkFilename);
                    if (Files.exists(chunkPath)) {
                        Files.copy(chunkPath, outputStream);
                    } else {
                        response.put("success", false);
                        response.put("message", "缺少分片文件: " + chunkFilename);
                        return ResponseEntity.badRequest().body(response);
                    }
                }
            }

            // 删除临时分片目录
            deleteDirectory(chunkDir);

            response.put("success", true);
            response.put("message", "文件合并成功");
            response.put("filename", uniqueFilename);
            response.put("originalFilename", filename);

            return ResponseEntity.ok(response);

        } catch (IOException e) {
            response.put("success", false);
            response.put("message", "合并文件失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 删除目录及其内容
     */
    private void deleteDirectory(Path directory) throws IOException {
        if (Files.exists(directory)) {
            Files.walk(directory)
                    .sorted(java.util.Comparator.reverseOrder())
                    .map(Path::toFile)
                    .forEach(java.io.File::delete);
        }
    }


}